﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Luna.Framework.Manifest;
using System.Windows.Forms;

namespace Luna.Framework.Impl {
	public class TemplateView : IView {

		public string Name {
			get;
			set;
		}

		public string Template { get; set; }

		public virtual bool IsShown {
			get {
				return false;
			}
		}

		public virtual Control getViewControl(IAppContext context, Control parent) {
			IManifest manifest = Framework.Manifest.getManifest(Template);
			if (manifest != null && manifest.Name.Equals("template")) {
				object controlObject = manifest.applyManifest(context);
				if (controlObject is Control) {
					Control control = controlObject as Control;
					control.Parent = parent;
					if (parent != null)
						parent.Controls.Add(control);
					return control;
				}
			}
			return null;
		}
	}

	public class SingletonTemplateView : TemplateView {
		private WeakReference refPointer;

		public override bool IsShown {
			get {
				return refPointer != null && refPointer.IsAlive && (refPointer.Target as Control).IsHandleCreated;
			}
		}

		public override Control getViewControl(IAppContext context, Control parent) {
			if (refPointer == null || !refPointer.IsAlive) {
				refPointer = new WeakReference(base.getViewControl(context, parent));
			}
			return refPointer.Target as Control;
		}
	}
}
